<template>
	<swiper class="home-swiper" :current="activeIndex" @change="change">
		<swiper-item class="swiper-item" v-for="(item, index) in tab" :key="index">
			<list-item :list="listCatchData[index]" :load="load[index]" @loadmore="loadmore"></list-item>
		</swiper-item>
	</swiper>
</template>

<script>
	import listItem from './list-item.vue'
	export default {
		components: {
			listItem
		},
		props: {
			tab: {
				type: Array,
				default: () => []
			},
			activeIndex: {
				type: Number,
				default: 0
			} 
		},
		data() {
			return {
				list: [],
				listCatchData: {},
				pageSize: 5,
				load: {}
			}
		},
		created () {
			uni.$on('changAticleLike', (types) => {
				if (types === 'follow') {
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				}
			})
		},
		watch: {
			tab: {
				handler (newVal) {
					if(newVal.length === 0) return
					this.listCatchData = {}
					this.load = {}
					this.getList(this.activeIndex)
				},
				deep: true
			}
 		},
		methods: {
			change (event) {
				const { current } = event.detail
				this.getList(current)
				this.$emit('change', current)
			},
			getList (current) {
				if (!this.load[current]) {
					const obj = {
						page: 1,
						loading: 'loading',
						beforePage: 0
					}
					this.load[current] = obj
				}
				const { name } = this.tab[current]
				this.$api.get_list({
					name,
					page: this.load[current].page,
					pageSize: this.pageSize
				}).then((res) => {
					const { data } = res
					console.log('data', data);
					const oldlist = this.listCatchData[current] || []
					if (data.length === 0) {
						let oldLoad = {}
						oldLoad.loading = 'noMore'
						oldLoad.page =  this.load[current].page
						this.$set(this.load, current, oldLoad)
						this.$forceUpdate()
						return
					}
					const {page, beforePage} = this.load[current]
					if ( page !== beforePage) {
						oldlist.push(...data)
						this.load[current].beforePage = beforePage + 1
					}
					this.$set(this.listCatchData, current, oldlist)
				})
			},
			loadmore () {
				const index = this.activeIndex
				if (this.load[index].loading === 'noMore') {
					return
				} else{
					let page = this.load[index].page
					page++
					this.load[index].page = page
					this.getList(index)
				}
			}
		}
	}
</script>

<style lang="scss">
	.home-swiper {
		height: 100%;
		.swiper-item {
			height: 100%;
			overflow: hidden;
			.list-scroll {
				height: 100%;
			}
		}
	}
</style>
